package com.gxy.learn.cu.utils.encrypt.aes;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * AES128 加解密工具类
 *
 * @author gxy
 */
public class Aes128Utils {

    private static final Logger log = LoggerFactory.getLogger(Aes128Utils.class);

    /**
     * 默认加密、解密秘钥
     */
    public static final String DEFAULT_SECRET_KEY = "F028%$#1702ES128";
    /**
     * 算法/加密模式/填充方式
     */
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    /**
     * AES 加密、解密秘钥长度需为16
     */
    private static final int SECURITY_KEY_LEN = 16;

    private static final String AES = "AES";

    /**
     * 加密Encoder
     */
    private static final BASE64Encoder base64Encoder = new BASE64Encoder();
    /**
     * 解密Encoder
     */
    private static final BASE64Decoder base64Decoder = new BASE64Decoder();

    /**
     * 加密
     *
     * @param content 需要加密的字符串
     * @param key     密钥
     * @return
     * @throws Exception
     */
    public static String encode(String content, String key) {
        if (StringUtils.isAllBlank(content, key) || key.length() != SECURITY_KEY_LEN) {
            log.error("待加密字符串[{}]串或秘钥[{}]错误！", content, key);
            return null;
        }
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES);
            // "算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8.displayName()));
            // 此处使用BASE64做转码功能，同时能起到2次加密的作用。
            return base64Encoder.encode(encrypted);
        } catch (Exception e) {
            log.error("待加密字符串[{}]进行AES128加密失败！", content, e);
            return null;
        }
    }

    /**
     * 解密
     *
     * @param content 需要解密的字符串
     * @param key     密钥
     * @return
     */
    public static String decode(String content, String key) {
        if (StringUtils.isAllBlank(content, key) || key.length() != SECURITY_KEY_LEN) {
            log.error("待解密字符串[{}]或秘钥[{}]错误！", content, key);
            return null;
        }
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            // 先用base64解密
            byte[] encrypted = base64Decoder.decodeBuffer(content);
            return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8.displayName());
        } catch (Exception e) {
            log.error("待解密字符串[{}]进行AES128解密失败！", content, e);
            return null;
        }
    }

    /**
     * 加密
     *
     * @param content 需要加密的字符串
     * @return
     * @throws Exception
     */
    public static String encode(String content) {
        return encode(content, DEFAULT_SECRET_KEY);
    }

    /**
     * 解密
     *
     * @param content 需要解密的字符串
     * @return
     */
    public static String decode(String content) {
        return decode(content, DEFAULT_SECRET_KEY);
    }

    public static void main(String[] args) {
        JSONObject js = new JSONObject();
        js.put("name", "巨魔战将");
        js.put("skill", "狂热");
        String content = js.toJSONString();
        log.info("待加密：{}", content);
        String encodeStr = encode(content);
        log.info("加密后:{}", encodeStr);
        log.info("解密后：{}", decode(encodeStr));

    }
}